package com.qys.livesMall.financial.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qys.livesMall.app.user.mapper.H2AppUserMapper;
import com.qys.livesMall.app.user.model.entity.H2AppUser;
import com.qys.livesMall.cache.RedisCache;
import com.qys.livesMall.common.exception.QysException;
import com.qys.livesMall.common.utils.MessageUtils;
import com.qys.livesMall.file.server.upload.model.entity.VideoStore;
import com.qys.livesMall.file.server.upload.service.VideoStoreService;
import com.qys.livesMall.financial.model.dto.sys.OfflineShortVideoQueryDTO;
import com.qys.livesMall.financial.model.dto.sys.OfflineShortVideoSaveDTO;
import com.qys.livesMall.financial.model.entity.OfflineShortVideo;
import com.qys.livesMall.financial.mapper.OfflineShortVideoMapper;
import com.qys.livesMall.financial.model.vo.app.APPOfflineShortVideoVO;
import com.qys.livesMall.financial.model.vo.sys.OfflineShortVideoVO;
import com.qys.livesMall.financial.service.OfflineShortVideoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qys.livesMall.framework.utils.SecurityUtils;
import com.qys.livesMall.shortVideo.constants.CacheConstants;
import com.qys.livesMall.shortVideo.mapper.H2ShortVideoTagMapper;
import com.qys.livesMall.shortVideo.model.entity.H2ShortVideo;
import com.qys.livesMall.shortVideo.model.entity.H2ShortVideoCategory;
import com.qys.livesMall.shortVideo.model.entity.H2ShortVideoComments;
import com.qys.livesMall.shortVideo.model.entity.H2ShortVideoTag;
import com.qys.livesMall.shortVideo.model.vo.app.AppShortVideoVO;
import com.qys.livesMall.shortVideo.service.IH2ShortVideoCategoryService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.redisnode.RedisCluster;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 理财视频 服务实现类
 * </p>
 *
 * @author 
 * @since 2023-07-31
 */
@Service
@Slf4j
public class OfflineShortVideoServiceImpl extends ServiceImpl<OfflineShortVideoMapper, OfflineShortVideo> implements OfflineShortVideoService {

    @Resource
    private  H2AppUserMapper appUserMapper;
    @Resource
    private VideoStoreService videoStoreService;
    @Resource
    private H2ShortVideoTagMapper h2ShortVideoTagMapper;
    @Resource
    private  IH2ShortVideoCategoryService videoCategoryService;
    @Resource
    private RedisCache redisCache;
    @Override
    public Page<OfflineShortVideoVO> pageBySystem(OfflineShortVideoQueryDTO queryDTO) {
        Page<OfflineShortVideoVO> voPage = baseMapper.pageBySystem(new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize()), queryDTO);

        List<OfflineShortVideoVO> records = voPage.getRecords();
        records.forEach(e->{
            String tagName = e.getTagName();
            if(StringUtils.isNotEmpty(tagName)){
                String[] split = tagName.split(",");
                e.setShortVideoCategoryName(List.of(split));
            }
        });

        return voPage.setRecords(records);
    }

    @Override
    public boolean saveVideoBySystem(OfflineShortVideoSaveDTO videoSaveDTO) {
        log.info("管理员操作短视频信息: {},--->{}", SecurityUtils.getUsername(), videoSaveDTO);

        OfflineShortVideo shortVideo = new OfflineShortVideo();
        BeanUtils.copyProperties(videoSaveDTO, shortVideo);
/*
        //用户信息
        H2AppUser h2AppUser = appUserMapper.selectById(SecurityUtils.getUserId());
        if (null == h2AppUser) {
            throw new QysException(MessageUtils.message("user.null"));
        }
        shortVideo.setAvatar(h2AppUser.getAvatar());
        shortVideo.setUserName(h2AppUser.getNickName());*/

        if (null == videoSaveDTO.getId()) {
            shortVideo.setCreateTime(LocalDateTime.now());
        }

        //封面图片
        shortVideo.setImg(getImg(shortVideo.getUrl()));
        if (null == shortVideo.getId()){
            save(shortVideo);
        }else {
            updateById(shortVideo);
        }

        //更新分类信息（视频标签）
        String videoCategoryId = videoSaveDTO.getShortVideoCategoryId();
        if (StringUtils.isNotEmpty(videoCategoryId) && null !=shortVideo.getId()) {

            //先删除视频和标签的绑定关系
            LambdaQueryWrapper<H2ShortVideoTag> updateWrapper = new LambdaQueryWrapper<>();
            updateWrapper.eq(H2ShortVideoTag::getVideoId, Long.valueOf(shortVideo.getId()));
            h2ShortVideoTagMapper.delete(updateWrapper);

            //从新保存标签绑定关系
            String[] split = videoCategoryId.split(",");
            for (String id : split) {
                H2ShortVideoCategory category = videoCategoryService.getById(id);
                if (null == category) {
                    throw new QysException("No short video classification information is obtained");
                }
                H2ShortVideoTag shortVideoTag = new H2ShortVideoTag();
                shortVideoTag.setVideoId(Long.valueOf(shortVideo.getId()));
                shortVideoTag.setTagCode(Long.valueOf(id));
                h2ShortVideoTagMapper.insert(shortVideoTag);
            }
        }
        return true;
    }

    @Override
    public APPOfflineShortVideoVO getOfflineShortVideoByApp() {
        long count = 1;
        while (true) {
            //删除缓存还是没有视频则报错
            if (count > 10) {
                return null;
            }
            //获取视频信息
            OfflineShortVideo video = baseMapper.randomOneVideo(SecurityUtils.getUserId());

            //获取不到视频将缓存数据全部删除
            if (count == 5 || null == video) {
                count++;
                redisCache.redisTemplate.delete(CacheConstants.APP_USER_OFFLINE_SHORT_VIDEO);
                continue;
            }
            //校验视频是否被看过
            Boolean member = redisCache.redisTemplate.opsForSet().isMember(CacheConstants.APP_USER_OFFLINE_SHORT_VIDEO,video.getId());
            if (Boolean.FALSE.equals(member)) {
                redisCache.redisTemplate.opsForSet().add(CacheConstants.APP_USER_OFFLINE_SHORT_VIDEO,video.getId());
                APPOfflineShortVideoVO appOfflineShortVideoVO=new APPOfflineShortVideoVO();
                BeanUtils.copyProperties(video, appOfflineShortVideoVO);
                return appOfflineShortVideoVO;
            }
            count++;
        }
    }

    private String getImg(String url) {
        VideoStore videoStore = videoStoreService.getOne(Wrappers.<VideoStore>query().eq("url", url));
        if (null != videoStore) {
            return videoStore.getImgUrl();
        }
        return null;
    }
}
